import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageWarehousOrderService } from '../../xstorage-manage-services/storage-warehous-order.service';

@Component({
  selector: 'app-storage-warehous-see',
  templateUrl: './storage-warehous-see.component.html',
  styleUrls: ['./storage-warehous-see.component.scss']
})
export class StorageWarehousSeeComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {};
  warehousTableData: any[] = [];

  putTypeOptions: any[] = []; // 入库类型
  warehouseOptions: any[] = []; // 入库仓库
  supplierOptions: any[] = []; // 供应商

  // SN信息 modal
  isSninfoVisible = false;
  snInfoItem: any = {
    tableData: []
  };

  // 多库位 Modal
  isDkwVisible = false;
  locationItem: any = {
    tableData: []
  };

  // 作废 Modal
  isZfVisible = false;
  submitZfLoading = false;
  toVoidItem: any = {};
  toVoidRemark = ''; // 作废备注

  constructor(
    private msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private commonService: CommonService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StorageWarehousOrderService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadPutTypeOptions();
    this.loadWarehouseOptions();
    this.loadSupplierList();
    this.loadDetailData();
  }

  // 入库类型options
  async loadPutTypeOptions() {
    const res: any = await this.commonService.getDictList('inbound_type');
    this.putTypeOptions = res || [];
  }

  // 查询仓库Options
  async loadWarehouseOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data.records || [];
    } else {
      this.msg.error(message);
    }
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res || [];
  }

  async loadDetailData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getWarehousingDetails(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const {list, warehousing} = data || {};

      this.detailsData = warehousing || {};
      this.detailsData.fileList = warehousing.contractEnclosure ? this.handleList(warehousing.contractEnclosure.split(',')) : [];
      this.warehousTableData = list || [];
    } else {
      this.msg.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  showTovoidModal(item: any) {
    this.toVoidItem = item;
    this.toVoidRemark = '';

    if (item.actualStorageNumber !== 0) {
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: '该行明细已有入库数量，建议提前核实，确认作废吗？',
        nzOkText: '确定',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.isZfVisible = true;
        },
        nzCancelText: '取消'
      });
    } else {
      this.isZfVisible = true;
    }
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      id: this.toVoidItem.id,
      state: 1, // 状态 0正常 1已作废
      note: this.toVoidRemark
    }
    this.submitZfLoading = true;
    const {code, message}: any = await this.services.warehousNullifyData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.msg.success('操作成功');
      this.loadDetailData();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * SN信息 Modal
   * ----------------------------------------------------------------
   */
  showSnInfoModal(item: any) {
    this.snInfoItem = item;
    this.snInfoItem.tableData = item.itemSns ? JSON.parse(item.itemSns) : [];
    this.isSninfoVisible = true;
  }

  /**
   * 多库位 Modal
   * ----------------------------------------------------------------
   */
  showLocationModal(item: any) {
    this.locationItem = item;
    this.locationItem.tableData = item.libraryText ? JSON.parse(item.libraryText) : [];
    this.isDkwVisible = true;
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  pageBack() {
    history.back();
  }

  coprText(str: string) {
    this.commonService.copyStr(str);
  }

  // 列合计
  calcSumTotal(key: string) {
    let sum = 0;
    const calcArrs = this.warehousTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 行小计
  calcProduct(num: number, price: number) {
    let pTotal = 0;
    pTotal = num * (price ? (Number(price)) : 0);

    return isNaN(pTotal) ? 0 : pTotal;
  }

  /**
   * 小计合计 实际入库 * 单价
   * @returns 
   */
  calcProductTotal() {
    let sum = 0;
    const calcArrs = this.warehousTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + ((item.actualStorageNumber || 0) * (item.price || 0));
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  downFile(item: any) {
    this.commonService.downLoadUrlFile(item.url);
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  handleList(arrs: Array<string>) {
    let newArr: Array<any> = [];
    if (arrs) {
      newArr = arrs.map(m => {
        let nArr = m.split('/');
        return {
          name: nArr[nArr.length - 1],
          url: m
        }
      })
    }

    return newArr;
  }
}
